package com.nonagon.melladesk.vo;

import com.nonagon.melladesk.entity.RoleEntity;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.data.annotation.Id;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.time.LocalDate;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author flitsneak
 * @ClassName security配置用户信息
 * @date 2021/3/22 15:56
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class UserDetail implements UserDetails {

    /**
     * 用户编号
     */
    @Id
    private String userId;
    /**
     * 设置编号
     */
    private Integer userSettingId;
    /**
     * 图片编号
     */
    private Integer imageId;
    /**
     * 邮箱
     */
    private String email;
    /**
     * 密码
     */
    private String hash;
    /**
     * 手机号码
     */
    private String phone;
    /**
     * 名
     */
    private String firstName;
    /**
     * 姓
     */
    private String lastName;
    /**
     * 国家
     */
    private String country;
    /**
     * 城市
     */
    private String city;
    /**
     * 州
     */
    private String state;
    /**
     * 邮政编码
     */
    private Integer zipcode;
    /**
     * 地址1
     */
    private String address1;
    /**
     *
     */
    private String address2;
    /**
     * 是否被删除，1删除，0未删除
     */
    private Integer isDeleted;
    /**
     * 1=封停账号，0=未封号
     */
    private Integer isLimit;
    /**
     * 创建时间
     */
    private LocalDate createTime;

    /**
     * 权限,采用set去重
     * @return
     */
    private Set<RoleEntity> roles;


    public UserDetail(String email,String hash,Set<RoleEntity> roles){
        this.email=email;
        this.hash=hash;
        this.roles=roles;
    }
    //鉴权
    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
       return this.roles
               .stream()
               .map(authority-> new SimpleGrantedAuthority(authority.getName()))
               .collect(Collectors.toCollection(HashSet::new));
    }

    @Override
    public String getPassword() {
        return hash;
    }

    @Override
    public String getUsername() {
        return email;
    }

    //账户过期
    @Override
    public boolean isAccountNonExpired() {
        return true;
    }

    //账户锁定冻结
    @Override
    public boolean isAccountNonLocked() {
        return true;
    }

    //账户授权过期，密码过期
    @Override
    public boolean isCredentialsNonExpired() {
        return true;
    }

    //账户删除
    @Override
    public boolean isEnabled() {
        return true;
    }
}
